# -*- coding: utf-8 -*-
"""
@File    :   __init__.py
@Time    :   2024/04/12 10:56:18
@Author  :   Ennis.Zhou 
@Desc    :   None
"""
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_session import Session
from flask_wtf import CSRFProtect
from flask_migrate import Migrate
from flask_cors import CORS
# from flask_login import LoginManager
from sqlalchemy import true
from config import BaseConfig

from logging.config import dictConfig

# 这里创建的三个扩展组件的对象都还是空对象，没有约束具体的app对象
db = SQLAlchemy()


def handle_exception(e):
    # 处理异常的逻辑
    return '出现异常：%s' % e


def create_app():
    app = Flask(__name__)
    app.json.ensure_ascii = False
    app.config.from_object(BaseConfig)
    db.init_app(app)
    # 初始化数据库
    migrate = Migrate()
    migrate.init_app(app, db)
    # 为flask补充csrf防护
    CSRFProtect(app)
    # 解决跨域的问题
    CORS(app, supports_credentials=true)
    # 利用flask-session，将session数据保存到redis中
    Session(app)
    # 注册models
    app.register_error_handler(Exception, handle_exception)
    # 注册蓝图
    from apps.User import user_v1
    from apps.Gallery import gallery_v1
    app.register_blueprint(user_v1, url_prefix="/api/v1")
    app.register_blueprint(gallery_v1, url_prefix="/api/v1")
    return app


dictConfig(
    {
        "version": 1,
        "disable_existing_loggers": False,
        "formatters": {  # 日志输出样式
            "default": {
                "format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
            }
        },
        "handlers": {
            "console": {
                "class": "logging.StreamHandler",  # 控制台输出
                "level": "DEBUG",
                "formatter": "default",
            },
            "log_file": {
                "class": "logging.handlers.RotatingFileHandler",
                "level": "INFO",
                "formatter": "default",  # 日志输出样式对应formatters
                "filename": "./log/flask.log",  # 指定log文件目录
                "maxBytes": 20 * 1024 * 1024,  # 文件最大20M
                "backupCount": 10,  # 最多10个文件
                "encoding": "utf8",  # 文件编码
            },
        },
        "root": {
            "level": "INFO",  # # handler中的level会覆盖掉这里的level
            "handlers": ["console", "log_file"],
        },
    }
)
